<template>
  <!-- 外层容器，居中布局 -->
  <div style="text-align: center">
    <!-- 步骤条外层容器，设置上下边距 -->
    <div style="margin: 30px 20px">
      <!-- 步骤条，根据 active 值控制步骤 -->
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="验证电子邮件" />
        <el-step title="重新设定密码" />
      </el-steps>
    </div>
    <!-- 第一步：验证电子邮件 -->
    <div style="text-align: center;margin: 0 20px;height: 100%" v-if="active===0">
      <!-- 标题和提示信息 -->
      <div style="margin-top: 80px">
        <div style="font-size: 25px;font-weight: bold">重置密码</div>
        <div style="font-size: 14px;color: grey">请输入需要重置密码的电子邮件地址</div>
      </div>
      <!-- 表单输入部分 -->
      <div style="margin-top: 50px ">
        <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
          <!-- 电子邮件输入框 -->
          <el-form-item prop="email">
            <el-input v-model="form.email" type="email" placeholder="电子邮件地址">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <!-- 验证码输入框和获取按钮 -->
          <el-form-item prop="code">
            <el-row :gutter="10" style="width: 100%">
              <el-col :span="17">
                <el-input v-model="form.code" :maxlength="6" type="text" placeholder="请输入验证码">
                  <template #prefix>
                    <el-icon><EditPen /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="5">
                <el-button type="success" @click="validateEmail"
                           :disabled="!isEmailValid || coldTime > 0">
                  {{coldTime > 0 ? '请稍后 ' + coldTime + ' 秒' : '获取验证码'}}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <!-- 提交按钮 -->
      <div style="margin-top: 70px">
        <el-button @click="confirmReset()" style="width: 270px;" type="danger" plain>开始重置密码</el-button>
      </div>
    </div>
    <!-- 第二步：设置新密码 -->
    <div style="text-align: center;margin: 0 20px;height: 100%" v-if="active===1">
      <!-- 标题和提示信息 -->
      <div style="margin-top: 80px">
        <div style="font-size: 25px;font-weight: bold">重置密码</div>
        <div style="font-size: 14px;color: grey">请填写您的新密码，务必牢记，防止丢失</div>
        <!-- 表单输入部分 -->
        <div style="margin-top: 50px">
          <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
            <!-- 新密码输入框 -->
            <el-form-item prop="password">
              <el-input v-model="form.password" :maxlength="16" type="password" placeholder="新密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <!-- 确认新密码输入框 -->
            <el-form-item prop="password_repeat">
              <el-input v-model="form.password_repeat" :maxlength="16" type="password" placeholder="重复新密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <!-- 提交按钮 -->
        <div style="margin-top: 70px">
          <el-button @click="doReset()" style="width: 270px;" type="danger" plain>立即重置密码</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { EditPen, Lock, Message } from "@element-plus/icons-vue";
import { get, post } from "@/net";
import { ElMessage } from "element-plus";
import router from "@/router";

// 当前步骤的索引
const active = ref(0)

// 表单数据对象
const form = reactive({
  email: '',
  code: '',
  password: '',
  password_repeat: '',
})

/**
 * 密码确认的验证函数
 * @param {Object} rule - 验证规则
 * @param {string} value - 用户输入的密码
 * @param {Function} callback - 回调函数，用于验证通过或不通过
 */
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮件地址', trigger: 'blur' },
    { type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: '请输入获取的验证码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码的长度必须在6-16个字符之间', trigger: ['blur'] }
  ],
  password_repeat: [
    { validator: validatePassword, trigger: ['blur', 'change'] },
  ],
}

// 表单引用，用于触发验证
const formRef = ref()
// 邮箱验证状态
const isEmailValid = ref(false)
// 验证码冷却时间
const coldTime = ref(0)

/**
 * 验证回调函数
 * @param {string} prop - 验证的属性名
 * @param {boolean} isValid - 验证是否有效
 */
const onValidate = (prop, isValid) => {
  if (prop === 'email')
    isEmailValid.value = isValid
}

/**
 * 触发邮箱验证并发送验证码
 */
const validateEmail = () => {
  coldTime.value = 60
  get(`/api/auth/ask-code?email=${form.email}&type=reset`, () => {
    ElMessage.success(`验证码已发送到邮箱: ${form.email}，请注意查收`)
    const handle = setInterval(() => {
      coldTime.value--
      if (coldTime.value === 0) {
        clearInterval(handle)
      }
    }, 1000)
  }, (message) => {
    ElMessage.warning(message)
    coldTime.value = 0
  })
}

/**
 * 确认重置步骤
 */
const confirmReset = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/reset-confirm', {
        email: form.email,
        code: form.code
      }, () => active.value++)
    }
  })
}

/**
 * 执行密码重置操作
 */
const doReset = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/reset-password', {
        email: form.email,
        code: form.code,
        password: form.password
      }, () => {
        ElMessage.success('密码重置成功，请重新登录')
        router.push('/')
      })
    }
  })
}

</script>

<style scoped>
/* 样式代码省略 */
</style>
